<template>
  <div class="search-container">
    <!-- 固定头部搜索框 -->
    <div class="search-header">
      <div class="back-btn" @click="$router.back()">
        <i class="fa-solid fa-angle-left"></i>
      </div>

      <div class="search-input-wrapper">
        <i class="fas fa-search search-icon"></i>
        <input
          v-model="searchText"
          class="search-input"
          type="text"
          placeholder="请输入搜索内容"
          @input="handleSearch"
          @keyup.enter="handleEnterSearch"
          @focus="inputFocused = true"
          @blur="inputFocused = false"
        />
        <i class="fa-solid fa-xmark clear-icon" v-if="searchText" @click="clearSearch"></i>
      </div>
      <div class="search-btn" @click="handleSearchClick">搜索</div>
    </div>

    <!-- 搜索历史 -->
    <div class="search-history" v-if="!searchText" v-show="!loading">
      <div class="history-header">
        <span class="section-title">搜索历史</span>
        <span class="clear-history" @click="clearHistory" v-if="searchHistory.length > 0">
          <i class="fa-solid fa-trash mr-1"></i> 清空
        </span>
      </div>
      <div class="history-list" v-if="searchHistory.length > 0">
        <div v-for="(item, index) in searchHistory" :key="index" class="history-item" @click="useHistoryItem(item)">
          <span>{{ item }}</span>
        </div>
      </div>
      <div class="empty-history mt-20" v-else>
        <i class="fa-solid fa-battery-empty text-5xl mb-8"></i>
        <p>没有搜索记录，请搜索您想看的好剧</p>
      </div>
    </div>

    <!-- 搜索结果列表 -->
    <transition name="fade">
      <div class="search-results" v-if="searchText && searchResults.length > 0">
        <div v-for="(item, index) in searchResults" :key="item.id" class="search-item" @click="handleResultClick(item)">
          <div class="item-content">
            <div class="cover-container">
              <img :src="item.cover" class="cover-img" :alt="item.title" />
            </div>
            <div class="item-info">
              <p class="item-title">{{ item.title }}</p>

              <p class="item-actor">
                <span v-for="actor in item.actors">{{ actor.name }}</span>
              </p>
            </div>
          </div>
        </div>
      </div>
    </transition>

    <!-- 骨架屏 - 搜索结果加载中 -->
    <div class="search-results skeleton-results" v-if="loading && searchText">
      <div v-for="i in 4" :key="i" class="search-item skeleton-item">
        <div class="item-content">
          <div class="cover-container skeleton-cover"></div>
          <div class="item-info">
            <div class="skeleton-title"></div>
            <div class="skeleton-actor">
              <span class="skeleton-tag"></span>
              <span class="skeleton-tag"></span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 无搜索结果提示 -->
    <transition name="fade">
      <div class="no-result" v-if="searchText && searchResults.length === 0 && !loading">
        <div class="no-result-icon">😕</div>
        <div>没有找到相关结果</div>
        <div class="no-result-tip">请尝试其他关键词</div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { searchDramas } from '@/apis/search'

const router = useRouter()

// 搜索相关变量
const searchText = ref('')
const searchResults = ref([])
const loading = ref(false)
const searchHistory = ref([])
const inputFocused = ref(false)

// 初始化
onMounted(() => {
  // 从本地存储获取搜索历史
  const history = localStorage.getItem('searchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }
})

// 跳转到播放器页面
const toPlayer = (id) => {
  router.push({ name: 'Player', params: { dramaId: id } })
}

// 处理搜索点击按钮
const handleSearchClick = () => {
  if (searchText.value.trim()) {
    // 执行搜索
    handleSearch()
    // 保存搜索历史
    saveSearchToHistory(searchText.value)
  } else {
    // 如果搜索框为空，相当于取消搜索
    cancelSearch()
  }
}

// 处理回车键搜索
const handleEnterSearch = () => {
  if (searchText.value.trim()) {
    // 执行搜索
    handleSearch()
    // 保存搜索历史
    saveSearchToHistory(searchText.value)
  }
}

// 处理搜索输入
const handleSearch = () => {
  if (searchText.value.trim() === '') {
    searchResults.value = []
    return
  }

  // 模拟搜索延迟
  loading.value = true
  setTimeout(async () => {
    const response = await searchDramas(searchText.value)
    searchResults.value = response.data?.list || []
    loading.value = false
  }, 300)
}

// 清空搜索内容
const clearSearch = () => {
  searchText.value = ''
  searchResults.value = []
}

// 使用历史搜索项
const useHistoryItem = (item) => {
  searchText.value = item
  handleSearch()
}

// 清空搜索历史
const clearHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('searchHistory')
}

// 点击搜索结果
const handleResultClick = (item) => {
  // 可以在这里添加导航到详情页的逻辑
  saveSearchToHistory(searchText.value)

  toPlayer(item.id)
}

// 保存搜索词到历史记录
const saveSearchToHistory = (text) => {
  if (!text.trim()) return

  // 如果已经存在，先删除旧的
  const index = searchHistory.value.indexOf(text)
  if (index !== -1) {
    searchHistory.value.splice(index, 1)
  }

  // 添加到最前面
  searchHistory.value.unshift(text)

  // 限制最多10条
  if (searchHistory.value.length > 10) {
    searchHistory.value = searchHistory.value.slice(0, 10)
  }

  // 保存到本地存储
  localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
}

// 返回上一页
const cancelSearch = () => {
  // 清空搜索框内容
  searchText.value = ''
  // 清空搜索结果
  searchResults.value = []
}
</script>

<style lang="scss" scoped>
.search-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #fff; // 修改为白色背景
  font-family:
    -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', sans-serif;

  .search-header {
    position: fixed;
    width: 100%;
    top: 0;
    display: flex;
    align-items: center;
    padding: 12px 10px;
    background-color: #fff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    z-index: 10;
    transition: all 0.3s ease;

    .back-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 36px;
      height: 36px;
      margin-right: 4px;
      color: #6b7280;
      font-size: 24px;
      border-radius: 50%;
      transition: all 0.2s;

      &:active {
        background-color: #f0f0f0;
      }
    }

    .search-input-wrapper {
      flex: 1;
      position: relative;
      display: flex;
      align-items: center;
      border-radius: 20px;
      transition: all 0.3s ease;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);

      .search-icon {
        position: absolute;
        left: 15px;
        font-size: 14px;
        color: #8a8a8a;
        transition: color 0.3s;
      }

      .search-input {
        width: 100%;
        height: 42px;
        padding: 0 40px 0 40px;
        border: none;
        border-radius: 21px;
        background-color: #f5f5f7;
        font-size: 15px;
        color: #333;
        outline: none;
        transition: all 0.3s;

        &::placeholder {
          color: #a0a0a0;
        }

        &:focus {
          background-color: #eef1f8;
          box-shadow: 0 0 0 2px rgba(58, 122, 254, 0.1);

          & + .search-icon {
            color: #3a7afe;
          }
        }
      }

      .clear-icon {
        position: absolute;
        right: 12px;
        width: 22px;
        height: 22px;
        line-height: 22px;
        text-align: center;
        border-radius: 50%;
        background-color: #c0c0c0;
        color: #fff;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.2s;

        &:active {
          transform: scale(0.9);
          background-color: #a0a0a0;
        }
      }
    }

    .search-btn {
      margin-left: 14px;
      color: #3a7afe;
      font-size: 15px;
      font-weight: 500;
      padding: 8px 4px;
      transition: opacity 0.2s;

      &:active {
        opacity: 0.7;
      }
    }
  }

  .search-history {
    padding: 16px;
    background-color: #fff; // 保持白色背景
    margin-top: 70px;
    border-radius: 0; // 移除圆角
    box-shadow: none; // 秾除阴影

    .history-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 15px;
      align-items: center;

      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
      }

      .clear-history {
        color: #666;
        font-size: 14px;
        display: flex;
        align-items: center;
        padding: 4px 8px;
        border-radius: 15px;
        background-color: #f5f5f5;

        .delete-icon {
          margin-right: 4px;
          font-size: 14px;
        }
      }
    }

    .history-list {
      display: flex;
      flex-wrap: wrap;

      .history-item {
        display: flex;
        align-items: center;
        padding: 8px 16px;
        background-color: #f0f2f5;
        border-radius: 18px;
        margin-right: 10px;
        margin-bottom: 10px;
        font-size: 14px;
        color: #333;
        transition: background-color 0.2s;

        .history-icon {
          margin-right: 6px;
          font-size: 14px;
        }

        &:active {
          background-color: #e6e6e6;
        }
      }
    }

    .empty-history {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 20px 0;
      color: #999;
      font-size: 14px;
    }
  }

  .search-results {
    display: flex;
    flex-direction: column;
    margin-top: 80px;
    gap: 16px;

    .search-item {
      background-color: white;
      border-radius: 8px;
      box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
      overflow: hidden;

      .item-content {
        display: flex;
        padding: 16px;

        .cover-container {
          width: 80px;
          height: 96px;
          background: linear-gradient(110deg, #f0f0f0 30%, #f8f8f8 50%, #f0f0f0 70%);
          border-radius: 8px;
          margin-right: 12px;
          flex-shrink: 0;
          position: relative;
          overflow: hidden;

          .cover-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          .duration-badge {
            position: absolute;
            bottom: 4px;
            right: 4px;
            background-color: rgba(0, 0, 0, 0.6);
            color: white;
            font-size: 12px;
            padding: 2px 4px;
            border-radius: 4px;
          }
        }

        .item-info {
          flex: 1;
          min-width: 0;
          display: flex;
          flex-direction: column;
          justify-content: center;

          span {
            font-weight: normal !important;
            font-size: 14px;
            background-color: #e6e6e6;
            padding: 2px 10px;
            border-radius: 10px;
          }

          .item-title {
            // font-weight: 500;
            color: #1f2937;
            margin: 0 0 4px 0;
          }

          .item-actor {
            margin-top: 6px;
            span {
              margin-right: 8px;
              color: #6b7280;
              font-size: 12px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }

          .item-footer {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .watch-time {
              font-size: 14px;
              color: #6b7280;
            }

            .delete-btn {
              color: #dc2626;
              font-size: 14px;
              background: none;
              border: none;
              cursor: pointer;
              padding: 4px;
            }

            .delete-btn:hover {
              color: #b91c1c;
            }
          }
        }
      }
    }
  }

  .no-result {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
    color: #666;
    font-size: 15px;

    .no-result-icon {
      font-size: 48px;
      margin-bottom: 16px;
    }

    .no-result-tip {
      margin-top: 8px;
      font-size: 14px;
      color: #999;
    }
  }

  // 骨架屏样式
  .skeleton-results {
    margin-top: 80px;
  }

  .skeleton-item {
    background-color: white !important;
  }

  .skeleton-cover {
    width: 80px;
    height: 96px;
    border-radius: 8px;
    margin-right: 12px;
    background: linear-gradient(110deg, #ececec 30%, #f5f5f5 50%, #ececec 70%);
    background-size: 200% 100%;
    animation: shimmer 1.5s infinite;
  }

  .skeleton-title {
    height: 18px;
    width: 70%;
    margin-bottom: 12px;
    border-radius: 4px;
    background: linear-gradient(110deg, #ececec 30%, #f5f5f5 50%, #ececec 70%);
    background-size: 200% 100%;
    animation: shimmer 1.5s infinite;
  }

  .skeleton-actor {
    display: flex;
    gap: 8px;

    .skeleton-tag {
      height: 20px;
      width: 60px;
      border-radius: 10px;
      background: linear-gradient(110deg, #ececec 30%, #f5f5f5 50%, #ececec 70%);
      background-size: 200% 100%;
      animation: shimmer 1.5s infinite;
      padding: 0 !important;
    }
  }

  @keyframes shimmer {
    0% {
      background-position: 200% 0;
    }
    100% {
      background-position: -200% 0;
    }
  }

  // 添加过渡动画
  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.3s;
  }
  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
  }
}
</style>
